// 统一的API客户端封装
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
}

export interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  headers?: Record<string, string>;
  body?: any;
  timeout?: number;
  retry?: number;
  onUploadProgress?: (progressEvent: ProgressEvent) => void;
}

class ApiClient {
  private baseURL: string;
  private defaultHeaders: Record<string, string>;
  private timeout: number;
  private retryCount: number;

  constructor(baseURL: string = '') {
    this.baseURL = baseURL;
    this.defaultHeaders = {
      'Content-Type': 'application/json',
    };
    this.timeout = 10000; // 10秒超时
    this.retryCount = 3;
  }

  // 设置认证token
  setAuthToken(token: string) {
    if (token) {
      this.defaultHeaders['Authorization'] = `Bearer ${token}`;
    } else {
      delete this.defaultHeaders['Authorization'];
    }
  }

  // 设置基础URL
  setBaseURL(url: string) {
    this.baseURL = url;
  }

  // 设置默认headers
  setDefaultHeaders(headers: Record<string, string>) {
    this.defaultHeaders = { ...this.defaultHeaders, ...headers };
  }

  // 请求拦截器
  private async requestInterceptor(url: string, options: RequestOptions) {
    // 可以在这里添加全局的请求处理逻辑
    // 比如添加认证token、记录日志等
    console.log(`[API Request] ${options.method} ${url}`);
    return { url, options };
  }

  // 响应拦截器
  private async responseInterceptor(response: Response) {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    // 处理业务错误码
    if (data.code !== 200 && data.code !== 0) {
      throw new Error(data.message || '请求失败');
    }
    
    return data;
  }

  // 错误处理
  private async errorHandler(error: any, url: string, options: RequestOptions, retry: number) {
    console.error(`[API Error] ${options.method} ${url}:`, error);
    
    // 如果是网络错误或超时，可以重试
    if (retry > 0 && (error.name === 'TypeError' || error.message.includes('timeout'))) {
      console.log(`[API Retry] ${options.method} ${url}, remaining retries: ${retry}`);
      await this.delay(1000); // 延迟1秒后重试
      return this.request(url, { ...options, retry: retry - 1 });
    }
    
    throw error;
  }

  // 延迟函数
  private delay(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  // 核心请求方法
  async request<T = any>(url: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const { method = 'GET', headers = {}, body, timeout = this.timeout, retry = this.retryCount } = options;
    
    // 处理URL
    const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`;
    
    // 请求拦截
    const { url: processedUrl, options: processedOptions } = await this.requestInterceptor(fullUrl, options);
    
    // 创建请求配置
    const requestOptions: RequestInit = {
      method,
      headers: { ...this.defaultHeaders, ...headers },
    };
    
    // 处理请求体
    if (body && method !== 'GET') {
      requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
    }
    
    try {
      // 创建超时控制器
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), timeout);
      requestOptions.signal = controller.signal;
      
      const response = await fetch(processedUrl, requestOptions);
      clearTimeout(timeoutId);
      
      // 响应拦截
      return await this.responseInterceptor(response);
    } catch (error) {
      // 错误处理
      return this.errorHandler(error, processedUrl, processedOptions, retry);
    }
  }

  // 快捷方法
  async get<T = any>(url: string, params?: Record<string, any>, options?: RequestOptions): Promise<ApiResponse<T>> {
    const queryString = params ? `?${new URLSearchParams(params).toString()}` : '';
    return this.request(`${url}${queryString}`, { ...options, method: 'GET' });
  }

  async post<T = any>(url: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request(url, { ...options, method: 'POST', body: data });
  }

  async put<T = any>(url: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request(url, { ...options, method: 'PUT', body: data });
  }

  async delete<T = any>(url: string, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request(url, { ...options, method: 'DELETE' });
  }

  async patch<T = any>(url: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request(url, { ...options, method: 'PATCH', body: data });
  }

  // 文件上传方法
  async upload<T = any>(url: string, formData: FormData, options?: RequestOptions): Promise<ApiResponse<T>> {
    const uploadOptions: RequestOptions = {
      ...options,
      method: 'POST',
      headers: {
        ...options?.headers,
      },
      body: formData,
    };
    
    // 移除Content-Type，让浏览器自动设置multipart/form-data
    delete uploadOptions.headers?.['Content-Type'];
    
    return this.request(url, uploadOptions);
  }
}

// 创建全局实例
export const apiClient = new ApiClient();

export default apiClient;